<template>
  <Dialog
    v-model="showModel"
    width="800px"
    title="配置会员价"
    @opened="handleOpened"
    @confirm="confirm"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
    >
      <product-switch
        v-model:model-value="form.enableMemberPrice"
        label-name="开启会员价格"
      />

      <template v-if="form.enableMemberPrice">
        <el-row>
          <el-col
            :span="4"
            class="title-col center-col"
          >
            <div>
              会员等级
            </div>
          </el-col>
          <el-col
            :span="4"
            class="title-col center-col"
          >
            <div>
              是否可购买
            </div>
          </el-col>
          <el-col
            :span="8"
            class="title-col center-col"
          >
            <div>
              金额 <span style="color: red">（元）</span>
            </div>
          </el-col>
          <el-col
            :span="8"
            class="title-col center-col"
          >
            <div>
              积分
            </div>
          </el-col>
        </el-row>

        <el-row
          v-for="(item, index) in form.priceEntities"
          :key="index"
        >
          <el-col
            :span="4"
            class="content-col center-col"
          >
            {{ item.memberName }}
          </el-col>
          <el-col
            :span="4"
            class="content-col center-col"
          >
            <el-switch
              v-model="item.onlyMembersCanBuy"
              :active-value="1"
              :inactive-value="0"
            />
          </el-col>
          <el-col
            :span="8"
            class="content-col center-col"
          >
            <el-form-item
              :prop="`priceEntities.${index}.payPrice`"
              :rules="[{
                validator: (rule, value, callback) => validatePayPrice(rule, value, callback, item, index),
                trigger: 'blur'
              }]"
            >
              <el-input
                v-model="item.payPrice"
                placeholder="请输入价格"
              />
            </el-form-item>
          </el-col>
          <el-col
            :span="8"
            class="content-col center-col"
          >
            <el-form-item
              :prop="`priceEntities.${index}.payOfCurrencyCount`"
              :rules="[{
                validator: (rule, value, callback) => validatePayOfCurrencyCount(rule, value, callback, item, index),
                trigger: 'blur'
              }]"
            >
              <el-input
                v-model="item.payOfCurrencyCount"
                placeholder="请输入积分"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6" />
        </el-row>
      </template>
    </el-form>
  </Dialog>
</template>

<script setup lang="ts">
import type { Ref, WritableComputedRef } from "vue";
import type { ICouponManageRow, IVipItem } from "@/api/modules/pointsMall";
import CustomerApi from "@/api/customerApi";
import { saveCouponVipPrice } from "@/api/pointsMall";
import ProductSwitch from "@/components/goodsCenter/addProductFormItem/ProductSwitch.vue";

const props = defineProps<{
  show: boolean;
  row: ICouponManageRow;
}>()

const emits = defineEmits<{
  (e: "update:show", val: boolean): void;
  (e: "finished"): void;
}>()

const showModel: WritableComputedRef<boolean> = computed({
  get() {
    return props.show;
  },
  set(val) {
    emits("update:show", val);
  }
})

const formRef = ref();
const form: Ref<{
  enableMemberPrice: boolean;
  priceEntities: IVipItem[];
}> = ref({
  enableMemberPrice: false,
  priceEntities: [],
});
const rules = ref({})

const queryVipMemInfo = async () => {
  const rs = await CustomerApi.queryVipMemInfo();
  if (rs.code == 200) {
    form.value.priceEntities = [
      {
        id: -1,
        memberName: "非会员",
        // onlyMembersCanBuy: 0,
        // payOfCurrencyCount: "",
        // payPrice: "",
      },
      ...(rs.payload ?? []),
    ]
    form.value.priceEntities.forEach(item => {
      item.memberId = item.id;
      const target = props.row.mallProductMemberPriceEntities?.find(pmItem => pmItem.memberId === item.memberId)

      if (target) {
        item.id = target.id;

        if (target.payPrice !== undefined) {
          item.payPrice = target.payPrice / 100
        }

        if (target.payOfCurrencyCount !== undefined) {
          item.payOfCurrencyCount = target.payOfCurrencyCount // 积分
        }

        if (target.onlyMembersCanBuy !== undefined) {
          item.onlyMembersCanBuy = target.onlyMembersCanBuy
        }
      }
    })
  }
};

watch(() => props.row, () => {
  form.value.enableMemberPrice = props?.row?.enableMemberPrice ?? 0
}, {
  immediate: true
})

const confirm = () => {
  if (form.value.enableMemberPrice) {
    const flag = form.value.priceEntities.some((item) => item.onlyMembersCanBuy);
    // 不存在开启会员购买
    if (!flag) {
      return ElMessage.error("请选择会员并配置会员价");
    }
  }

  const _form = {}
  _form.goodsId = props.row.id;   // 优惠券ID
  _form.enableMemberPrice = form.value.enableMemberPrice;
  _form.priceEntities = form.value.priceEntities.map(item => ({
    ...item,
    payPrice: parseInt((item.payPrice * 100).toFixed(2).slice(0, -3))
  }))

  formRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      const rs = await saveCouponVipPrice(_form);
      if (rs.code === 200) {
        ElMessage.success("保存成功");
        showModel.value = false;
        emits("finished")
      }
    }
  })
}

const validatePayOfCurrencyCount = (rule: any, value: any, callback: any, item: any, index: number) => {
  if (!item.onlyMembersCanBuy || /^[1-9]\d*$/.test(value) || +item.payOfCurrencyCount > 0) {
    callback()
  } else {
    if (+item.payPrice) {
      formRef.value.clearValidate()
      callback()
    } else {
      callback('请设置金额或积分')
    }
  }
}

const validatePayPrice = (rule: any, value: any, callback: any, item: any, index: number) => {
  if (!item.onlyMembersCanBuy || /^[1-9]\d*$/.test(value) || +item.payPrice > 0) {
    callback()
  } else {
    if (+item.payOfCurrencyCount) {
      formRef.value.clearValidate()
      callback()
    } else {
      callback('请设置金额或积分')
    }
  }
}

const handleOpened = () => {
  queryVipMemInfo();
}
</script>

<style scoped lang="scss">
.center-col {
  display: flex;
  align-items: center;
  justify-content: center;
}

.title-col {
  height: 50px;
  background: #cccccc;
}

.content-col {
  height: 50px;

  :deep(.el-form-item) {
    margin-bottom: 0;
  }
}
</style>
